package com.xunlai.infra.permission.manager.config;

import com.xunlai.infra.permission.business.controller.MemberController;
import com.xunlai.infra.permission.common.exception.ExceptionCodeEnum;
import com.xunlai.infra.permission.common.vo.BaseResponse;
import com.xunlai.infra.permission.manager.authority.web.LoginController;
import com.xunlai.infra.permission.manager.web.controller.AdminUserController;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * @author liang
 * @date 9/18/23 9:00 PM
 */
@ControllerAdvice(basePackageClasses = {LoginController.class, AdminUserController.class, MemberController.class})
@Slf4j
public class AdminManagerControllerAdvice extends ResponseEntityExceptionHandler {

    @ResponseBody
    @ExceptionHandler({Throwable.class})
    public ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
        HttpStatus status = getStatus(request);
        log.error(ex.getMessage(),ex);
        return new ResponseEntity<>(BaseResponse.error(ExceptionCodeEnum.SERVER_ERROR), status);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer code = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        HttpStatus status = code == null ? null : HttpStatus.resolve(code);
        return (status != null) ? status : HttpStatus.INTERNAL_SERVER_ERROR;
    }
}
